package it.trick.admin.service;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import it.trick.admin.App;
import it.trick.admin.Constants;
import it.trick.admin.Util;
import it.trick.admin.model.ChapterModel;
import it.trick.admin.model.ContentsBaseModel;
import java.net.URL;

public class CategoryService {

    /**
     * カテゴリリストの取得
     * @param site
     * @param channel
     * @return
     * @throws Exception
     */
    public static List<ContentsBaseModel> getList(String channel) throws Exception {

        String json = Http.get(App.getInstance().getSite() + Constants.GET_CATEGORY_LIST_PATH + channel);
        Type collectionType = new TypeToken<Collection<ContentsBaseModel>>() {
        }.getType();

        Gson gson = new Gson();

        List<ContentsBaseModel> modelList = gson.fromJson(json, collectionType);

        return modelList;
    }

    /**
     * カテゴリの追加
     * @return
     */
    public static ContentsBaseModel addCategory(ContentsBaseModel model) throws Exception {

        URL postURL = new URL(App.getInstance().getSite() + Constants.ADD_CATEGORY_PATH);
        Type responseModelType = new TypeToken<ContentsBaseModel>() {}.getType();

        //POSTの内容を書き出す
        StringBuilder psb = new StringBuilder();
        psb.append("channel=");
        psb.append(model.getPrarentKeyString());
        psb.append("&");
        psb.append("name=");
        psb.append(model.getName());
        psb.append("&");
        psb.append("index=");
        psb.append(model.getIndex());

        return (ContentsBaseModel)Http.postGetResponseJson(postURL, psb.toString(), responseModelType);
    }

    /**
     * 更新
     * @param chapterModel
     * @throws Exception
     */
    public static void updateCategory (
            ContentsBaseModel contentsBaseModel) throws Exception {

        URL postURL = new URL(App.getInstance().getSite() + Constants.UPDATE_CATEGORY_PATH);

        //POSTの内容を書き出す
        StringBuilder psb = new StringBuilder();
        psb.append("category=");
        psb.append(contentsBaseModel.getKeyValueString());
        psb.append("&");
        psb.append("name=");
        psb.append(contentsBaseModel.getName());
        psb.append("&");
        psb.append("index=");
        psb.append(contentsBaseModel.getIndex());

        Http.postOnle(postURL, psb.toString());
    }

    /**
     * カテゴリ削除
     * @param site
     * @param categoryKeyString
     */
    public static void deleteCategory(String KeyString) throws Exception {

        URL postURL = new URL(App.getInstance().getSite() + Constants.DELETE_CATEGORY_PATH);

        //POSTの内容を書き出す
        StringBuilder psb = new StringBuilder();
        psb.append("category=");
        psb.append(KeyString);

        Http.postOnle(postURL, psb.toString());
    }
}
